package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

/**
 * 设备管理Service业务层处理
 *
 * @author guomo
 * @date 2025-10-18
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTdacLient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备列表。
     * 根据提供的设备对象，检索符合条件的数据记录。
     *
     * @param device 设备对象，包含查询条件
     * @return List<Device> 查询到的设备列表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步物联网产品列表到缓存中。
     *
     * @throws BaseException 如果从物联网平台获取产品列表失败。
     */
    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        ListProductsResponse response = ioTdacLient.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网产品同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    /**
     * 返回所有产品信息的列表。
     *
     * @return List<ProductVo> 返回包含所有产品信息的列表，如果缓存中没有产品信息则返回空列表。
     */
    @Override
    public List<ProductVo> allProduct() {
        String productsJson = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (productsJson != null) {
            return JSONUtil.toList(productsJson, ProductVo.class);
        }
        return List.of();
    }

    /**
     * 注册设备信息。
     * @param dto DeviceDto类型的对象，包含设备信息。
     * @throws BaseException 如果设备名称、设备标识或同一位置有相同设备则抛出异常。
     */
    @Override
    public void register(DeviceDto dto) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, dto.getDeviceName());
        Device one = this.getOne(queryWrapper);
        if (one != null) {
            throw new BaseException("设备名称不能重复!");
        }
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getNodeId, dto.getNodeId());
        one = this.getOne(queryWrapper1);
        if (one != null) {
            throw new BaseException("设备标识不能重复!");
        }
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getRemark, dto.getRemark());
        queryWrapper2.eq(Device::getProductKey, dto.getProductKey());
        one = this.getOne(queryWrapper2);
        if (one != null) {
            throw new BaseException("同一位置不能有相同设备!");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(dto.getNodeId());
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setProductId(dto.getProductKey());
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDevice.setDescription(dto.getDeviceDescription());
        request.setBody(addDevice);
        AddDeviceResponse response = ioTdacLient.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("设备注册失败");
        }
        Device device = new Device();
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        device.setBindingLocation(dto.getBindingLocation() + "");
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.productKey);
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setNodeId(dto.getNodeId());
        device.setRemark(dto.getRemark());
        this.save(device);
    }
    /**
     * 获取设备详细信息。
     * @param iotId 设备的唯一标识符
     * @return DeviceDetailVo 设备详细信息对象
     * @throws BaseException 如果IoT ID参数异常或设备查询不到
     */
    @Override
    public DeviceDetailVo getDeviceInfo(String iotId) {
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = ioTdacLient.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("参数异常");
        }
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device one = this.getOne(queryWrapper);
        if (one == null) {
            throw new BaseException("设备查询不到");
        }
        DeviceDetailVo detailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        LocalDateTime activeTime = null;
        if (activeTimeStr != null) {
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        }
        detailVo.setActiveTime(activeTime);

        return detailVo;
    }

    /**
     * 查询指定IoT设备的属性信息。
     * @param iotId IoT设备的唯一标识符。
     * @return 返回包含设备属性信息的DeviceDataVo列表。
     * @throws BaseException 如果IoT设备ID无效或日期解析出现异常。
     */
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTdacLient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("参数异常");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        String eventTimeStr = reported.getEventTime();
        if (eventTimeStr == null) {
            throw new BaseException("日期解析异常");
        }
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);
        return  getDeviceDataVos(reported, eventTime);
    }

    /**
     * 将设备属性转换为设备数据列表。
     *
     * @param reported 设备属性对象
     * @param eventTime 事件时间
     * @return 转换后的设备数据列表
     */

    private  List<DeviceDataVo> getDeviceDataVos(DeviceShadowProperties reported, LocalDateTime eventTime) {
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) reported.getProperties();
        Set<String> sets = properties.keySet();
        sets.forEach(key -> {
                    DeviceDataVo deviceDataVo = new DeviceDataVo();
                    deviceDataVo.setFunctionId(key);
                    deviceDataVo.setEventTime(eventTime);
                    deviceDataVo.setValue(properties.get(key));
                    deviceDataVoList.add(deviceDataVo);
                }
        );
        return deviceDataVoList;
    }

    /**
     * 更新设备信息。
     * @param dto 设备传输对象，包含设备信息，如iotId、设备名称、设备描述等。
     * @throws BaseException 如果设备更新失败，将抛出此异常。
     */
    @Override
    public void updateDevice(DeviceDto dto) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getRemark, dto.getRemark());
        queryWrapper.eq(Device::getLocationType,dto.getLocationType());
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        queryWrapper.ne(Device::getIotId,dto.getIotId());
        Device one = this.getOne(queryWrapper);
        if (one!=null) {
            throw new BaseException("同一位置不能有相同设备!");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.iotId);
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(dto.getDeviceName());
        updateDevice.setDescription(dto.getDeviceDescription());
        request.setBody(updateDevice);
        UpdateDeviceResponse response = ioTdacLient.updateDevice(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("更新失败");
        }
        Device device = BeanUtil.toBean(dto, Device.class);
        this.updateById(device);
    }

    /**
     * 删除指定物联网设备。
     * @param iotId 设备的唯一标识符。
     * @throws BaseException 如果删除操作失败。
     */
    @Override
    public void deleteDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = ioTdacLient.deleteDevice(request);
        if(response.getHttpStatusCode()!=204){
            throw new BaseException("删除失败");
        }
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        this.remove(queryWrapper);
    }

    /**
     * 查询产品信息。
     * @param productKey 产品的唯一标识符。
     * @return 返回产品的服务能力列表。
     * @throws BaseException 如果获取产品信息时发生异常，将抛出此异常。
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = ioTdacLient.showProduct(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("获取产品信息异常");
        }
        List<ServiceCapability> list = response.getServiceCapabilities();

        return AjaxResult.success(list);
    }
}
